import store from '@/store'
import axios from 'axios'
import util from '@/libs/util'
import Setting from '@/setting'
import SettingEnv from '@/setting.env'
import { Notice } from 'view-design'
import { Message } from 'element-ui'

// 创建一个错误
function errorCreate (msg) {
  const err = new Error(msg)
  errorLog(err)
}
// 记录和显示错误
function errorLog (err) {
  // 添加到日志
  store.dispatch('admin/log/push', {
    message: '数据请求异常',
    type: 'error',
    meta: {
      error: err
    }
  })
  // 打印到控制台
  if (process.env.NODE_ENV === 'development') {
    util.log.error('>>>>>> Error >>>>>>')
  }
  // 显示提示，可配置使用 iView 的 $Message 还是 $Notice 组件来显示
  if (Setting.errorModalType === 'Message') {
    if (err.message !== '') {
      if (err.response && err.response.status === 401) {
        window.location.href = SettingEnv.publicPath + 'login'
      } else {
        Message.error({
          message: err.message,
          type: 'error',
          customClass: 'element_message_error'
        })
      }
    }
  } else if (Setting.errorModalType === 'Notice') {
    Notice.error({
      title: '提示',
      desc: err.message,
      duration: Setting.modalDuration
    })
  }
}
// 创建一个 axios 实例
const service = axios.create({
  baseURL: Setting.apiBaseURL,
  timeout: 7200000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在请求发送之前做一些处理
    return config
  },
  error => {
    // 发送失败
    Promise.reject(error)
  }
)

const UsercenterEnum = {
  Code: 'code',
  Data: 'data',
  Msg: 'msg',
  Success: '0',
  Error: '4004'
}

const SysbackEnum = {
  Code: 'retStatus',
  Data: 'retData',
  Msg: 'retMessage',
  Success: '1',
  Error: '2'
}

const ValidateEnum = {
  Usercenter: dataAxios => validateExecutor(dataAxios, UsercenterEnum),
  Sysback: dataAxios => validateExecutor(dataAxios, SysbackEnum)
}

const validateExecutor = (dataAxios, System) => {
  const code = dataAxios[System.Code]
  const msg = dataAxios[System.Msg]
  const data = dataAxios[System.Data]
  if (code === System.Success) return dataAxios
  if (code === System.Error) {
    errorCreate(msg)
    return dataAxios
  }
  if (!data) errorCreate(msg)
  return dataAxios
}

const responseUseExecutor = (dataAxios) => {
  const { code, retStatus } = dataAxios
  if (code === undefined && retStatus === undefined) return dataAxios // 如果没有 code 代表这不是项目后端开发的接口
  // 有 code 代表这是一个后端接口 可以进行进一步的判断
  if (code) return ValidateEnum.Usercenter(dataAxios) // 用户中心
  if (retStatus) return ValidateEnum.Sysback(dataAxios) // 商品中心
  return dataAxios
}

// 响应拦截器
service.interceptors.response.use(
  response => {
    const dataAxios = response.data
    return responseUseExecutor(dataAxios)
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          break
        case 401:
          error.message = '您还未登录或者登录超时'
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器内部错误'
          break
        case 501:
          error.message = '服务未实现'
          break
        case 502:
          error.message = '网关错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
          break
      }
    }
    errorLog(error)
    return Promise.reject(error)
  }
)

export default service
